package cloudPayAdmin.util.jsonFilter;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import org.apache.commons.lang.StringUtils;
import com.alibaba.fastjson.serializer.ValueFilter;
import cloudPayAdmin.util.annotation.FenToYuanTransfer;

public class FenToYuanFilter implements ValueFilter {

	@Override
	public Object process(Object object, String name, Object value) {
		if(value != null) {
			
			try {
				Class valueClazz = value.getClass();
				Field field = object.getClass().getDeclaredField(name);
				
				Method method = null;
				
				if(valueClazz==boolean.class || valueClazz == Boolean.class) {
					try {
						method = object.getClass().getMethod("get" + StringUtils.upperCase(StringUtils.substring(name,0,1)) + StringUtils.substring(name, 1,name.length()));
					} catch (NoSuchMethodException e) {
						method = object.getClass().getMethod("is" + StringUtils.upperCase(StringUtils.substring(name,0,1)) + StringUtils.substring(name, 1,name.length()));
					}
				} else {
					method = object.getClass().getMethod("get" + StringUtils.upperCase(StringUtils.substring(name,0,1)) + StringUtils.substring(name, 1,name.length()));
				}
			
				if(field.getAnnotation(FenToYuanTransfer.class) != null || method.getAnnotation(FenToYuanTransfer.class) != null) {
					FenToYuanTransfer ytft = field.getAnnotation(FenToYuanTransfer.class) == null ? method.getAnnotation(FenToYuanTransfer.class) : field.getAnnotation(FenToYuanTransfer.class);
					
					if(ytft.reverse() == false) {   //如果是 分转元
						
						if(valueClazz == Integer.class || valueClazz == int.class || valueClazz == Long.class || valueClazz == long.class) {
							
							return new BigDecimal(value+"").divide(new BigDecimal("100")).setScale(2).toString();
							
						} else {
							return value;
						}
						
					} else {     //如果是元 转分
						
						if(valueClazz == Float.class || valueClazz == float.class || valueClazz == double.class || valueClazz == Double.class) {
							
							return new BigDecimal(value+"").multiply(new BigDecimal("100")).setScale(2).toString();
							
						} else {
							return value;
						}						
					}
				}
			
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			return value;
		} else {
			return value;
		}
		
	}

}
